package com.yoga.admin.api.annotation;

import com.yoga.common.appexception.AppErrorCodeEnum;
import com.yoga.common.appexception.AppException;
import com.yoga.common.bo.YogaAdminBO;
import com.yoga.common.util.Config;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.core.MethodParameter;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;


public class LoginUserHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {

    private ValueOperations valueOperations;

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        //拦截添加注解的方法参数
        return parameter.getParameterType().isAssignableFrom(YogaAdminBO.class) && parameter.hasParameterAnnotation(LoginUser.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer container,
                                  NativeWebRequest request, WebDataBinderFactory factory) throws Exception {

        String yogaAdminId =(String) request.getHeader(Config.YOGA_ADMIN_ID);

        if (StringUtils.isEmpty(yogaAdminId)){
            throw new AppException(AppErrorCodeEnum.UN_LOGN);
        }
        if (valueOperations==null){
            BeanFactory beanFactory = WebApplicationContextUtils
                    .getRequiredWebApplicationContext(request.getNativeRequest(HttpServletRequest.class).getServletContext());

            RedisTemplate redisTemplate= (RedisTemplate) beanFactory.getBean("stringRedisTemplate");
            valueOperations=redisTemplate.opsForValue();
        }

        YogaAdminBO yogaAdminBO= UserTokenManage.getInstance(valueOperations).getLoginUser(Long.parseLong(yogaAdminId));
        if (yogaAdminBO==null){
            throw new AppException(AppErrorCodeEnum.UN_LOGN);
        }
        return yogaAdminBO;
    }


}

